<template>
  <el-row :gutter="10">
    <el-col :span="8">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="申领单号" prop="applyNo">
            <el-input v-model="queryParams.applyNo" class="width-120" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="confirmType">
            <el-select v-model="queryParams.confirmType" class="width-120" clearable @change="getList">
              <el-option label="确认出库" value="1"/>
              <el-option label="已发送" value="2"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-form-item label="申领时间" prop="applyTime">
          <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                          range-separator="截止" start-placeholder="开始日期" type="daterange"
                          @change="timeChange"></el-date-picker>
        </el-form-item>
      </el-row>
      <el-button class="mb5" type="primary"
                 @click="getList">
        <template #icon>
          <i-ep-search/>
        </template>
        刷新
      </el-button>
      <div class="mb20">
        <el-table v-adaptive :border="true" :data="stagingList" :header-cell-style="$headerCellStyle"
                  @row-click="stagingMaster">
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领单号"
                           prop="applyNo"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="供货单位"
                           prop="storageFromName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领科室"
                           prop="storageName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领时间"
                           min-width="130px"
                           prop="applyTime"/>
          <el-table-column :align="'center'" fixed="right" label="状态" prop="confirmType" width="85px">
            <template #default="scope">
              <span v-if="scope.row.confirmType ==='0'" style="color:#d20303">未确认</span>
              <span v-if="scope.row.confirmType ==='1'" style="color:#023aa4">确认出库</span>
              <span v-if="scope.row.confirmType ==='2'" style="color:#027e1d">申领已发送</span>
              <span v-if="scope.row.confirmType ==='4'" style="color:#a95602">撤销</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领操作人"
                           min-width="90px"
                           prop="createByName">
          </el-table-column>
                    <el-table-column
                      :align="'left'" class-name="small-padding fixed-width"
                      fixed="right"
                      label="操作"
                      width="45"
                    >
                      <template #default="scope">
                        <el-tooltip
                          v-if="scope.row.confirmType ==='2'"
                          class="item"
                          content="删除"
                          effect="dark"
                          placement="top"
                        >
                          <el-button circle type="danger" @click="handleDeleteApply(scope.row)">
                            <template #icon>
                              <i-ep-delete/>
                            </template>
                          </el-button>
                        </el-tooltip>
                      </template>
                    </el-table-column>
        </el-table>
        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize"
                    v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList"/>
      </div>
    </el-col>
    <el-col :span="16">
      <el-row class="mb5">
        <el-button type="primary" @click="submitForm">
          确认出库
        </el-button>
      </el-row>
      <el-table v-adaptive="10" :border="true" :data="form.stagingListDetail"
                :header-cell-style="$headerCellStyle" :stripe="true"
                default-expand-all highlight-current-row>
        <el-table-column fixed="left" label="出库明细" type="expand" width="75">
          <template #default="props">
            <div m="4">
              <el-table :data="props.row.itemVoList" header-cell-class-name="requiredClass">
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价"
                                 prop="purchasePrice"
                                 width="100px">
                  <template #default="scope">
                    <el-form-item :prop="'itemVoList.' + scope.$index + '.purchasePrice'"
                                  class="table-form-margin">
                      <span>{{ scope.row.purchasePrice }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="比例" prop="proportion"
                                 width="80px">
                  <template #default="scope">
                    <el-form-item :prop="'itemVoList.' + scope.$index + '.proportion'"
                                  class="table-form-margin">
                      <el-select ref="ratio" v-model="scope.row.proportion" disabled filterable
                                 placeholder="请选择比例" style="width: 100%">
                        <el-option v-for="dict in dictDataMap['price_ratio']" :key="dict.dictValue"
                                   :label="dict.dictLabel"
                                   :value="dict.dictValue"></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价"
                                 prop="retailPrice"
                                 width="100px">
                  <template #default="scope">
                    <el-form-item :prop="'itemVoList.' + scope.$index + '.retailPrice'"
                                  class="table-form-margin">
                      <span>{{ scope.row.retailPrice }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号" prop="batchNo"
                                 width="140px">
                  <template #default="scope">
                    <el-form-item :prop="'itemVoList.' + scope.$index + '.batchNo'"
                                  class="table-form-margin">
                      <span>{{ scope.row.batchNo }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库数量" prop="quantity"
                                 width="120px">
                  <template #default="scope">
                    <el-form-item :prop="'itemVoList.' + scope.$index + '.quantity'"
                                  class="table-form-margin">
                      <el-input v-model="scope.row.quantity" :disabled="scope.row.confirmType == '1'"
                                class="table-input"
                                clearable @blur="quantityBlur(scope.row)">
                        <template #append>
                          <dict-data-tag v-if="scope.row.packSize === '2'" :options="dictDataMap['spec_unit']"
                                         :value="scope.row.packageUnits"/>
                          <dict-data-tag v-else :options="dictDataMap['spec_unit']"
                                         :value="scope.row.minUnits"/>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="现有库存" prop="packageUnits"
                                 width="120">
                  <template #default="scope">
                    <span>{{ scope.row.quantityAndUnits }}</span>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期"
                                 prop="produceDate"
                                 width="150px">
                  <template #default="scope">
                    <el-form-item :prop="'itemVoList.' + scope.$index + '.produceDate'">
                      <el-date-picker v-model="scope.row.produceDate"
                                      :disabled="true" clearable
                                      placeholder="生产日期" style="width: 100%" type="date"
                                      value-format="YYYY-MM-DD">
                      </el-date-picker>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期" prop="expireDate"
                                 width="150px">
                  <template #default="scope">
                    <el-form-item :prop="'itemVoList.' + scope.$index + '.expireDate'">
                      <el-date-picker v-model="scope.row.expireDate" :disabled="true"
                                      clearable placeholder="有效期"
                                      style="width: 100%"
                                      type="date" value-format="YYYY-MM-DD">
                      </el-date-picker>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column v-if="!props.detailId"
                                 :align="'center'"
                                 class-name="small-padding fixed-width" label="操作"
                                 width="80">
                  <template #default="scope">
                    <el-tooltip v-if="scope.row.confirmType != '1'" class="item" content="删除"
                                effect="dark"
                                placement="top">
                      <el-button circle type="danger"
                                 @click="handleDelete(scope.$index,props.$index,scope.row)">
                        <template #icon>
                          <i-ep-delete/>
                        </template>
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编号"
                         min-width="60px"
                         prop="serialNumber">
          <template #default="scope">
            <span class="ys-css" style="font-weight: bold">{{ scope.row.serialNumber }}</span>
          </template>
        </el-table-column>

        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品名称"
                         min-width="180px"
                         prop="drugName">
          <template #default="scope">
            <span class="ys-css" style="font-weight: bold">{{ scope.row.drugName }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装规格"
                         min-width="120px"
                         prop="packageSpec">
          <template #default="scope">
            <span class="ys-css" style="font-weight: bold">{{
                scope.row.packSize === '2' ? scope.row.packageSpec : scope.row.minSpec
              }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领数量"
                         min-width="90px"
                         prop="quantity">
          <template #default="scope">
            <div>
              <dict-data-tag v-if="scope.row.packSize === '2'"
                             :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                             class="mb-10 mr10" style="float: right"/>
              <dict-data-tag v-else :options="dictDataMap['spec_unit']"
                             :value="scope.row.minUnits" class="mb-10 mr10"
                             style="float: right"/>
              <div class="mr20" style="float: right; font-weight: bold">
                {{ scope.row.quantity }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领备注"
                         min-width="130px"
                         prop="remarks">
          <template #default="scope">
            <span class="ys-css" style="font-weight: bold">{{ scope.row.remarks }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家"
                         min-width="120px"
                         prop="firmName">
          <template #default="scope">
            <span class="ys-css" style="font-weight: bold">{{ scope.row.firmName }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领时间"
                         min-width="130px"
                         prop="applyTime">
          <template #default="scope">
            <span class="ys-css" style="font-weight: bold">{{ scope.row.applyTime }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'right'" class-name="small-padding fixed-width" header-align="center"
                         label="操作" width="60">
          <template #default="scope">
            <el-tooltip class="item"
                        content="添加出库明细"
                        effect="dark" placement="bottom">
              <el-button circle type="primary"
                         @click="addItem(scope.$index,scope.row)">
                <template #icon>
                  <i-ep-plus/>
                </template>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <el-dialog
    v-model="dialogVisible"
    :before-close="handleClose"
    title="出库药品选择"
    width="58%"
  >
    <el-table :border="true" :data="autoExportTable" :header-cell-style="$headerCellStyle"
              :stripe="true" default-expand-all
              height="400px" highlight-current-row @row-click="autoRowClick">
      <el-table-column label="药品名称" prop="drugName" width="160"/>
      <el-table-column label="药品别名" prop="drugNameAlias" width="150"/>
      <el-table-column label="药品编码" prop="drugCode" width="110"/>
      <el-table-column label="包装规格" prop="packageSpec" width="130"/>
      <el-table-column label="现有库存" prop="quantityAndUnits" width="130">
        <template #default="scope">
          <span style="color: #0066FF">{{ scope.row.quantityAndUnits }}</span>
        </template>
      </el-table-column>
      <el-table-column label="包装单位" prop="currentUnits" width="120">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.currentUnits"/>
        </template>
      </el-table-column>
      <el-table-column label="进货价(元)" prop="tradePrice" width="110"/>
      <el-table-column label="零售价(元)" prop="retailPrice" width="110"/>
      <el-table-column label="厂商" prop="firmName" width="190"/>
      <el-table-column label="批号" prop="batchNo" width="120"/>
      <el-table-column label="包装数量" prop="packageNum" width="90"/>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="dialogOk">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user.ts";
import {delDrugApplyFor, listDrugApplyFor, selectPageDrugApplyFor} from "@/api/drug/drugApplyFor.ts";
import {addDrugApplyForDetail, delDrugApplyForDetail} from "@/api/drug/drugApplyForDetail.ts"
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {autoExportList} from "@/api/drug/drugStock";

const dictStore = useDictStoreHook();
const dictDataMap = ref(
  dictStore.isTypeGetData("spec_unit")
);

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;

const {proxy} = getCurrentInstance() as any;

// 出库自动补全列表
const autoExportTable = ref<any>([]);
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  orgId: userInfo.orgId,
  storageFrom: proxy.$currentSelectDept,
  // confirmType: "2"
  confirmTypeArray: ["2", "1"]
});
// 出库药品索引（点击增加药品）
const drugInfoIndex = ref<number>(0);
// 暂存列表查询参数
const detailQuery = ref<any>({
  applyId: "",
});
const dialogVisible = ref(false)
const form = ref<any>({
  stagingListDetail: []
})

const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);

// 暂存列表
const stagingList = ref<any>([]);

const itemAutomatic = ref<any>();
// 暂存申领明细列表
const stagingListDetail = ref<any>([]);
// 总条数
const total = ref(0);

function timeChange(e) {
  if (e) {
    dateRange.value = [proxy.$parseTime(e[0], "{y}-{m}-{d} 00:00:00"), proxy.$parseTime(e[1], "{y}-{m}-{d} 23:59:59")]
  }
  getList()
}

/** 查询药品申领暂存列表 */
function getList() {
  selectPageDrugApplyFor(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    stagingList.value = response.rows;
    total.value = response.total;
  });
}


/** 暂存列表主记录点击事件 */
async function stagingMaster(row) {
  detailQuery.value.applyNo = row.applyNo;
  detailQuery.value.orgId = row.orgId;
  form.value.storageId = row.storageId;
  form.value.receiverId = row.storageId;
  form.value.storageFrom = row.storageFrom;
  form.value.receiverUserId = row.createBy;
  form.value.applyNo = row.applyNo;
  form.value.confirmType = row.confirmType;
  form.value.orgId = userInfo.orgId;
  await getListDetail();
}


async function getListDetail() {
  await listDrugApplyFor(detailQuery.value).then((response: any) => {
    form.value.stagingListDetail = response.data;
    form.value.stagingListDetail.forEach((item: any) => {
      if (item.packSize === '2') {
        item.quantity = item.quantity / item.packageNum;
      }
      // item.itemVoList = []
    })
  });
  return form.value.stagingListDetail;
}


function handleClose() {
  dialogVisible.value = false
}

function dialogOk() {
  handleClose()
}


/**
 * 确认出库
 */
function submitForm() {
  let saveDetailList: any = []
  for (const item of form.value.stagingListDetail) {
    let itemNo: number = 1
    let quantity = item.packSize === '2' ? item.quantity * item.packageNum : item.quantity;
    let totalQuantity = item.itemVoList.reduce((sum: number, item: any) => {
      if (item.packSize === '2') {
        return sum + (Number(item.quantity) || 0) * item.packageNum;
      } else {
        return sum + (Number(item.quantity) || 0);
      }
    }, 0);
    console.log(item);
    if (totalQuantity > quantity) {
      return ElMessage.error('【' + item.drugName + "】出库数量不能大于申请数量")
    }
    for (const itemVo of item.itemVoList) {
      itemNo++
      itemVo.masterId = item.applyId
      itemVo.itemNo = itemNo
      saveDetailList.push(itemVo)
    }
  }
  if (saveDetailList.length <= 0) {
    return ElMessage.error("出库药品明细为空，不能确认")
  }

  const data = {
    storageId: form.value.storageId,
    applyNo: form.value.applyNo,
    storageFrom: form.value.storageFrom,
    receiverId: form.value.receiverId,
    receiverUserId: form.value.receiverUserId,
    saveDetailList: saveDetailList,
    orgId: userInfo.orgId,
  }
  addDrugApplyForDetail(data).then(() => {
    ElMessage.success("确认成功")
    getList()
    getListDetail()
  })
}

/** 项目名称自动补全检索 */
function itemNameInput(event, _value) {
  form.value.itemName = event;
  autoExportListFun();
}

/**
 * 单行出库药品明细数量校验
 * @param row
 */
function quantityBlur(row) {
  if (Number(row.quantity) > Number(row.quantityExisting)) {
    return ElMessage.error("出库数量不能大于现有库存数量")
  }
}

/** 药品自动补全点击事件 */
function autoRowClick(obj) {
  console.log("obj", obj)
  nextTick(() => {
    if (obj) {
      const existInfo = form.value.stagingListDetail[drugInfoIndex.value].itemVoList.filter((item: any) => {
        return item.batchNo === obj.batchNo;
      })
      if (existInfo.length > 0) {
        let alikeBatchNo: number = 0;
        existInfo.forEach(item => {
          alikeBatchNo += item.packSize === '2' ? Number(item.quantity) * Number(item.packageNum) : Number(item.quantity);
        })
        if (alikeBatchNo >= (obj.packSize === '2' ? Number(obj.quantity) * Number(obj.packageNum) : Number(obj.quantity))) {
          return ElMessage.error("该批号" + obj.batchNo + "药品已经添加的出库数量>=现有库存数量，库存不足，不能添加！")

        }
        // return ElMessage.error("该批号" + obj.batchNo + "药品已存在，不能重复添加！")
      }
      let itemVoList = {
        itemInfo: obj.drugName,
        drugInfoId: obj.drugInfoId,
        itemDrug: obj.drugName,
        drugCode: obj.drugCode,
        orgId: obj.orgId,
        packageSpec: obj.packageSpec,
        minSpec: obj.minSpec,
        minUnits: obj.minUnits,
        retailPrice: obj.retailPrice,
        proportion: "1",
        firmId: obj.firmId,
        firmName: obj.firmName,
        packageNum: obj.packageNum,
        drugPriceId: obj.drugPriceId,
        expireDate: obj.expireDate,
        produceDate: obj.produceDate,
        purchasePrice: obj.tradePrice,
        batchNo: obj.batchNo,
        quantityAll: obj.quantityAll,
        packSize: obj.packSize,
        stockId: obj.stockId,
        currentSpec: obj.currentSpec,
        currentUnits: obj.currentUnits,
        packageUnits: obj.packageUnits,
        quantityAndUnits: obj.quantityAndUnits,
        quantityExisting: obj.quantity,
        confirmType: ""
      }
      form.value.stagingListDetail[drugInfoIndex.value].itemVoList.push(itemVoList);
      autoExportTable.value = []
      handleClose()
    }
  });
}


/**
 * 添加出库明细
 * @param index
 * @param row
 */
function addItem(index: number, row: any) {
  const itemVoListLen = form.value.stagingListDetail[index].itemVoList.length
  if (itemVoListLen > 0 && !form.value.stagingListDetail[index].itemVoList[itemVoListLen - 1].quantity) {
    return ElMessage.error("请输入出库数量后，再添加！")
  }
  // 计算 row.itemVoList 中 quantity 的合计数量
  const totalQuantity = row.itemVoList.reduce((sum, item) => {
    if (item.packSize === '2') {
      return sum + (Number(item.quantity) || 0) * item.packageNum;
    } else {
      return sum + (Number(item.quantity) || 0);
    }
  }, 0);
  if (totalQuantity > (row.packSize === '2' ? row.quantity * row.packageNum : row.quantity)) {
    return ElMessage.error("药品【" + row.drugName + "】出库数量不能大于申领数量")
  }
  dialogVisible.value = true;
  form.value.storageId = row.storageFrom;
  form.value.itemName = row.drugName;
  form.value.firmId = row.firmId;
  drugInfoIndex.value = index;
  autoExportListFun()
}


// 查询出库药品字典
function autoExportListFun() {
  const data = {
    orgId: queryParams.value.orgId,
    storageId: form.value.storageId,
    itemInfo: form.value.itemName,
    firmId: form.value.firmId,
  }
  autoExportList(data).then((res: resType) => {
    autoExportTable.value = res.data;
  })
}


/**
 * 删除出药品申领记录详情表
 * @param index
 * @param item
 */
function handleDeleteApply(item: any) {
  ElMessageBox.confirm('确定要删除本条记录吗？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delDrugApplyFor(item.applyNo).then(() => {
        form.value.stagingListDetail = []
        getList()
        ElMessage.success("删除成功");
      })
    })
}

/**
 * 明细删除
 * @param index
 * @param propsIndex
 * @param _row
 */
function handleDelete(index: number, propsIndex: number, row: any) {
  ElMessageBox.confirm('确定要删除本条记录吗？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      if (row.detailId) {
        delDrugApplyForDetail(row.detailId).then(() => {
        })
        form.value.stagingListDetail[propsIndex].itemVoList.splice(index, 1);
      }
      ElMessage.success("删除成功");
    })
}


getList()

</script>

<script lang="ts">
export default {
  name: "ConfirmExport",
}
</script>
<style scoped>
:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.table-input .el-input__wrapper) {
  background-color: #ff000017;
}

</style>
